<template>
	<view class="register-pay page">
		<view class="register-pay-title">
			<view class="flexR">
				<text>预约确认</text>
				<!-- <view class="register-pay-title-btn" @click="onCancle" v-if="(fromYYZT!='1')&&params">
					取消
				</view> -->
			</view>
		</view>
		<view class="register-pay-main">
			<view class="register-pay-main-info">
				<view class="register-pay-main-info-box">
					<view class="circle"></view>
					<u-section title="预约信息" font-size='32' :right="false" :bold='true' :line-color='themeColorLight' color="#000000"></u-section>
					<view class="base-card">
						<view class="card-row">
							<label>预约科室：</label>{{routeParams.ksmc}}
						</view>
						<view class="card-row">
							<label>医生姓名：</label>{{routeParams.ysmc}}
						</view>
						<view class="card-row" v-if="routeParams.ghrq">
							<label>预约时间：</label>{{routeParams.ghrq|transRQ}}
						</view>
						<view class="card-row" v-if="routeParams.ghsjd">
							<label>就诊时段：</label>{{routeParams.ghsjd}}
						</view>
					</view>
					<u-section title='就诊人信息' font-size='32' :right="false" :bold='true' :line-color='themeColorLight' color="#000000"></u-section>
					<view class="base-card">
						<view class="card-row">
							<label>就&nbsp;&nbsp;诊&nbsp;人：</label>{{userInfo.name}}
						</view>
						<view class="card-row">
							<label>就诊卡号：</label>{{userInfo.cardNo}}
						</view>
						<view class="card-row">
							<label>性&emsp;&emsp;别：</label>{{userInfo.sex}}
						</view>
					</view>
					<u-section v-if="params" title="其他信息" font-size='32' :right="false" :bold='true' :line-color='themeColorLight' color="#000000"></u-section>
					<view class="base-card" v-show="params">
						<view class="card-row">
							<label>挂&nbsp;&nbsp;号&nbsp;费：</label>￥{{params.ghf||routeParams.ghf||'0'}}
						</view>
						<view class="card-row">
							<label>诊&nbsp;&nbsp;疗&nbsp;费：</label>￥{{params.zlf||routeParams.zlf||'0'}}
						</view>
						<view class="card-row">
							<label>应收金额：</label>￥{{params.ysje||'0'}}
						</view>
						<view class="card-row">
							<label>总&nbsp;&nbsp;金&nbsp;额：</label>￥{{params.zje||'0'}}
						</view>
					</view>
					<view class="reminder">
						<view class="reminder-title">
							温馨提示
						</view>
						<view class="reminder-content">
							已锁定成功，请在10分钟内支付（如果页面退出，可在个人中心-我的挂号里面支付），否则订单取消。
						</view>
					</view>
				</view>
			</view>
			<view class="register-pay-btn" @click="onPay">
				<view class="theme-light-btn" :style="{opacity:params?'1':'0.4'}">
					去支付
				</view>
			</view>
		</view>
		<Loading :load='load' />
	</view>
</template>

<script>
	import { themeColorLight} from '@/static/js/theme.js'
	import Loading from '@/components/Load/index.vue'
	import { getAppointment, cancelAppointment, poPayRegister } from '@/api/register.js'
	import { mapGetters, mapActions } from 'vuex'
	import dayjs from 'dayjs'
	import tradePay from '@/utils/pay.js'
	import { getPayStatusMY } from "@/api/system.js"
  import UserDate from '@/components/UserInfo/user-date.vue'
  
	export default {
		components:{Loading, UserDate},
		data() {
			return {
				themeColorLight,
				load:false,
				params:'',
				routeParams:'',
				fromYYZT:0, // 预约状态1 表示从我的挂号页面来 不需要展示取消预约 因为我的挂号页面已展示了取消按钮
				timeNumber:10000,
				timer:null
			}
		},
		computed:{
			...mapGetters(['userInfo'])
		},
		async onLoad(op) {

			if(op.yyzt){
				this.fromYYZT = op.yyzt
				if(op.yyzt==1){
					this.routeParams = JSON.parse(op.params)
				}
			}else if(op.params){
				this.routeParams = JSON.parse(op.params)
			} 
			await this.$onLaunched
			if(!this.userInfo.patId){
				// uni.navigateTo({
				// 	url:'/pages/Login/index'
				// })
				return
			}
			this.initData()
		},
		filters:{
			transRQ(val){
				return dayjs(val).format('YYYY-MM-DD')
			}
		},
		methods: {
			...mapActions(['createPay']),
			onPay(){
				if(!this.params){
					return
				}
				if(this.params.ysje===0){
					this.toRegister()
				}else{
					this.toPay()
				}
				
			},
			toRegister(){
				let params = {
					ysje:this.params.ysje,
					patId:this.userInfo.patId,
					sjh:this.params.sjh,
					yyxh:this.params.yyxh,
					ghxh:this.params.ghxh,
				}
				this.load = true;
				poPayRegister(params).then(data => {
					this.load = false
					this.$u.toast('预约挂号成功！')
					uni.reLaunch({
						url:'/pages/Index'
					})
				}).catch(e => {
					this.load = false
				})
			},
			toPay(){
				let params = {
					money:this.params.ysje,
					patId:this.userInfo.patId,
					sjh:this.params.sjh,
					tradeType:1,
				}
				this.load = true;
				this.createPay(params).then((data)=>{
					this.load = false;
					let paymentData;
					// #ifdef MP-ALIPAY
					paymentData = data.tradeNo
					// #endif
					// #ifndef MP-ALIPAY
					paymentData = {
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.weChatPackage,
						signType: data.signType ,
						paysign: data.paySign
					}
					// #endif
					if(paymentData){
						// #ifdef MP-ALIPAY
						tradePay(paymentData, status => {
							let info = {
								outTradeNo:data.outTradeNo
							}
							this.getStatus(info, 1000)
						})
						// #endif
						// #ifndef MP-ALIPAY
						tradePay(paymentData)
						// #endif
					}else{
						this.$u.toast('系统错误')
					}
				}).catch(e => {
					this.load = false
				})
			},
      toPay() {
				let params = {
					money:this.params.ysje,
					patId:this.userInfo.patId,
					sjh:this.params.sjh,
					tradeType:1,
				}
				this.load = true;
				this.createPay(params).then((data)=>{
					this.load = false;
					let paymentData;
					paymentData = {
            body: data.hisOrderId,
            orderId: data.hisOrderId,
            // payMoney: this.params.ysje,
            payMoney: '0.01',
            spbCreIp: '127.0.0.1',
            openId: this.userInfo.userId,
            account: this.userInfo.userId
					}
          
          pay(paymentData).then(res => {
            this.onBridgeReady(res)
          })
				}).catch(e => {
					this.load = false
				})
			},
      pay() {
        const data = {
          body: this.pkg.pkgName,
          orderId: this.opt.orderId,
          // payMoney: this.params.ysje,
          payMoney: '0.01',
          spbCreIp: '127.0.0.1',
          openId: this.userInfo.userId,
          account: this.userInfo.userId
        }
        pay(data).then(res => {
          this.onBridgeReady(res)
        })
      },
      onBridgeReady(res) {
          WeixinJSBridge.invoke('getBrandWCPayRequest', {
              "appId": res.appId,     //公众号ID，由商户传入     
              "timeStamp": res.timeStamp,     //时间戳，自1970年以来的秒数     
              "nonceStr": res.nonceStr,      //随机串     
              "package": res.package,
              // "signType": "RSA",     //微信签名方式：     
              "signType": "MD5",     //微信签名方式：
              "paySign": res.paySign //微信签名 
          },
          function(res) {
              if (res.err_msg == "get_brand_wcpay_request:ok") {
                  // 使用以上方式判断前端返回,微信团队郑重提示：
                  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                  // alert('跳转成功页面')
                  
                  this.$u.toast('支付成功')
                  uni.redirectTo({
                  	url:'/pages/Index'
                  })
              }
          });
      },
			// 轮询
			getStatus(info, refreshTime){
				this.load = true
				this.timer = setInterval(()=>{
					if(this.timeNumber<0){
						this.clearTimer()
						this.$u.toast('业务处理状态未知，请以具体消息通知为准')
					}
					this.timeNumber -= refreshTime
					getPayStatusMY(info).then(data => {
						if(data){
							let msg = ''
							if(data.tradeStatus==='WAIT_BUYER_PAY'||data.tradeStatus==='TRADE_CLOSED'){
								this.$u.toast('用户未支付')
								this.clearTimer()
							}else{
								if(data.payStatus===4){
									this.clearTimer()
									this.$u.toast('支付成功')
									uni.redirectTo({
										url:'/pages/Index'
									})
								}else if(data.payStatus===7){
									this.clearTimer()
									this.$u.toast('业务处理失败，已退款')
								}
							}
						}else{
							this.clearTimer()
						}
					}).catch( e=> {
						this.clearTimer()
					})
				}, refreshTime)
			},
			// 清除计时器
			clearTimer(){
				this.load = false
				if(this.timer){
					clearInterval(this.timer)
					this.timer = null
				}
			},
			initData(){
				this.load = true;
				getAppointment({...this.routeParams}).then(data => {
					this.load = false
					this.params = data||''
				}).catch(e => { 
					this.load = false
					this.params = ""
					if(e.retCode === 'C0006'){
						this.$u.toast('用户已预约，请前往我的挂号信息中完成支付')
						uni.redirectTo({
							url:'/pages/Personal/Myregister/index'
						})
					}
			    })
			},
			onCancle(){
				let params = {
					ghrq:this.params.ghrq,
					patId:this.userInfo.patId,
					yyxh:this.params.yyxh
				}
				this.load = true
				cancelAppointment(params).then(data => {
					this.load = false
					this.$u.toast('预约取消成功')
					uni.navigateBack()
				}).catch(e => {
					this.load = false
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.register-pay{
		position: relative;
		height: calc(100vh);
		.register-pay-title{
			height: 210rpx;
			background-color: $theme-color-light;
			color: $text-color-fff;
			padding: 40rpx 30rpx;
			font-size: 32rpx;
			.flexR{
				height: 80rpx;
				justify-content: space-between;
				align-items: center;
				>.register-pay-title-btn{
					font-size: 28rpx;
					padding: 10rpx 30rpx;
					border: 1px solid $text-color-fff;
					border-radius: 6rpx;
				}
			}
		}
		.register-pay-main{
			position: absolute;
			top: 150rpx;
			left: 0;
			width: calc(100vw - 80rpx);
			margin: 0 40rpx;
		}
		.register-pay-main-info{
			padding: 40rpx;
			box-sizing: border-box;
			max-height: calc(100vh - 150rpx - 180rpx);
			background-color: $uni-bg-color;
			>.register-pay-main-info-box{
				max-height: calc(100vh - 150rpx - 250rpx);
				overflow: scroll;
			}
			.circle{
				position: absolute;
				height: 40rpx;
				width: 40rpx;
				border-radius: 50%;
				left: calc(50% - 20rpx);
				top: -20rpx;
				background-color: $theme-color-light;
			}
			.base-card{
				padding: 30rpx 20rpx;
			}
			.reminder{
				border: 1px solid #FFAB73;
				background-color: #FFFEE8;
				padding: 20rpx;
				>.reminder-content{
					color: $text-color;
				}
			}
		}
		.register-pay-btn{
			height: 90rpx;
			margin-top: 40rpx;
			>view{
				height: 90rpx;
			}
		}
	}
</style>
